package main

import (
	"fmt"
	"go-ocr/db"
	"go-ocr/db/dao"
	"go-ocr/db/model"
	"go-ocr/global"
	"go-ocr/image"
	"log"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/viper"
)

var Cfg *viper.Viper = nil

func main() {
	//err := godotenv.Load()
	//if err != nil {
	//	log.Fatal("Error loading .env file")
	//}
	err := initConfig()
	if err != nil {
		panic("配置文件加载失败")
	}
	// 初始化数据库
	db.Init()
	// 创建一个每隔 10 秒钟触发一次的定时器
	timer := time.NewTicker(10 * time.Second)
	imagePath := "1.png"
	point := image.Point{X: global.Conf.Screenshot.X, Y: global.Conf.Screenshot.Y}
	for _ = range timer.C {
		image.GenerateScreen(point, imagePath)
		text := image.ConvertImageToText(imagePath)

		strs := strings.Split(text, "\r\n")
		for i := len(strs) - 1; i >= 0; i-- {
			if strs[i] == "" {
				strs = append(strs[:i], strs[i+1:]...)
			}
		}
		if len(strs) == 4 {
			for i := 0; i < 4; i++ {
				saveMeasureInfo(strings.ReplaceAll(strings.ReplaceAll(strs[i], " ", ""), ",", "."), strconv.FormatInt(int64(i+1), 32))
			}
		} else {
			fmt.Println("识别到的字符串没有 4行")
		}
	}
}

func saveMeasureInfo(str string, dataItemNumber string) {
	if str == "" {
		return
	}

	f, err := strconv.ParseFloat(str, 32)
	if err != nil {
		fmt.Println("转换成浮点型错误")
		return
	}
	dataItemInfo, _ := dao.DataItemService.DataItem(dataItemNumber)

	measureInfo := model.MeasureInfo{}
	measureInfo.DeviceNumber = "9999"
	measureInfo.DataNumber = dataItemNumber
	measureInfo.Value = strconv.FormatFloat(f, 'g', 6, 32)
	measureInfo.CreateDate = time.Now().Format("2006-01-02 15:04:05")
	if dataItemInfo.AlarmState == "1" && (f < dataItemInfo.AlarmMin || f > dataItemInfo.AlarmMax) {
		measureInfo.IsStandard = "1"
	} else {
		measureInfo.IsStandard = "0"
	}
	err = dao.MeasureInfoService.Insert(&measureInfo)
	if err != nil {
		fmt.Println("存储失败")
	}
}

func initConfig() error {
	Cfg = viper.New()
	Cfg.SetConfigName("config.toml")
	Cfg.AddConfigPath(".")
	Cfg.SetConfigType("toml")
	if err := Cfg.ReadInConfig(); err != nil {
		log.Fatal("read config failed,err:", err)
	}
	Cfg.Unmarshal(&global.Conf)
	return nil
}
